﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using DataAccess;
using com.chttl.ienc.bean;
using java.util;
using Microsoft.Reporting.WebForms;
using System.IO;
using Ionic.Zip;
using System.Drawing;

namespace iEN.Report
{
    public partial class OnlinePayment : System.Web.UI.Page
    {
        //初始頁面
        protected void Page_Load(object sender, EventArgs e)
        {
            Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            if (!this.Page.IsPostBack)//先判斷是否已經登入過
            {
                if (Session["LoginName"] == null)
                {
                    Response.Write("<script>alert('請先登入！！');location.href='../Login.aspx';</script>");
                }

                //權限判斷
                //Operator : 可查詢、匯出、列印報表。   Session["SysAdmin"]=1
                //Director : 管理者，可使用所有功能。   Session["SysAdmin"]=2
                string sSysAdmin = Session["SysAdmin"].ToString();
                if (sSysAdmin != "1" && sSysAdmin != "2")
                {
                    ErrorMsg("您沒有使用此頁面的權限，請聯絡系統管理員！");
                    btnQuery.Visible = false;
                    return;
                }

                tbDegree.Text = "0";
                Session["FolderName"] = Session.SessionID.ToString();
                lOldDegree.Text="";
                Intialize();    //初始化控制項
            }
        }

        /// <summary>
        /// 初始化控制項
        /// </summary>
        private void Intialize()
        {
            //取得大樓名稱
            ddlBuilding.Items.Clear();
            ddlBuilding.Items.Add("---");
            DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(1);  //取得Level=1的大樓資訊
            for (int i = 0; i < dtOrgGroup.Rows.Count; i++)
            {
                ListItem li = new ListItem(dtOrgGroup.Rows[i]["_name"].ToString().Trim(), dtOrgGroup.Rows[i]["_id"].ToString());
                ddlBuilding.Items.Add(li);
            }
            ddlBuilding.SelectedIndex = 0;

            btnQuery.Attributes["onclick"] = ";document.getElementById('Loading').style.visibility='visible';";
        }

        /// <summary>
        /// 重新選擇大樓
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlBuilding_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlFloor.Items.Clear();
            ddlFloor.Items.Add("---");
            if (ddlBuilding.SelectedItem.Text != "---")
            {
                string sID = ddlBuilding.SelectedItem.Value;
                DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(2);  //取得Level=2的樓層資訊
                dtOrgGroup.DefaultView.Sort = " _name";
                dtOrgGroup = dtOrgGroup.DefaultView.ToTable();

                IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                             where sID.Contains(r.Field<Int32>("_parent_id").ToString())
                                             select r;
                foreach (DataRow r in query)
                {
                    ListItem li = new ListItem(r["_name"].ToString().Trim(), r["_id"].ToString());
                    ddlFloor.Items.Add(li);
                }
            }
            UpdatePanel3.Visible = false;
        }

        /// <summary>
        /// 重新選擇樓層
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlFloor_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlRoom.Items.Clear();
            ddlRoom.Items.Add("---");
            if (ddlFloor.SelectedItem.Text != "---")
            {
                string sID = ddlFloor.SelectedItem.Value;
                DataTable dtOrgGroup = new DBAccess().getOrgGroupTableByLevel(3);  //取得Level=3的寢室資訊
                dtOrgGroup.DefaultView.Sort = " _name";
                dtOrgGroup = dtOrgGroup.DefaultView.ToTable();

                IEnumerable<DataRow> query = from r in dtOrgGroup.AsEnumerable()
                                             where sID.Contains(r.Field<Int32>("_parent_id").ToString())
                                             select r;
                foreach (DataRow r in query)
                {
                    ListItem li = new ListItem(r["_name"].ToString().Trim(), r["_id"].ToString());
                    ddlRoom.Items.Add(li);
                }
            }
            UpdatePanel3.Visible = false;
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                UpdatePanel3.Visible = false;
                lblResult.Text = "設定成功";

                if (ddlBuilding.SelectedItem.Text == "---")
                {
                    ErrorMsg("請選擇欲設定的大樓！");
                    return;
                }
                if (ddlFloor.SelectedItem.Text == "---")
                {
                    ErrorMsg("請選擇欲設定的樓層！");
                    return;
                }
                if (ddlRoom.SelectedItem.Text == "---")
                {
                    ErrorMsg("請選擇欲設定的寢室！");
                    return;
                }
                if (ddlDevice.SelectedItem.Text == "---")
                {
                    ErrorMsg("請選擇欲設定的電錶！");
                    return;
                }
                if (tbDegree.Text == "")
                {
                    ErrorMsg("請設定欲存入的度數！");
                    return;
                }

                double oldDegree = new DBAccess().getMeterBalance(ddlDevice.SelectedItem.Value);
                double degree = double.Parse(tbDegree.Text) + oldDegree;
                bool blnRet = new DBAccess().setMeterBalance( ddlDevice.SelectedValue, degree );

                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "大樓名稱：" + ddlBuilding.SelectedItem.Text + " 樓層：" + ddlFloor.SelectedItem.Text + " 寢室名稱：" + ddlRoom.SelectedItem.Text + " 電錶：" + ddlDevice.SelectedItem.Text;

                if (blnRet == false)
                {
                    new DBAccess().addEventLog(strAccount, strIP, 200, strMemo + " 線上繳費失敗 (原有度數：" + oldDegree.ToString() + "度)", "0", Convert.ToInt32(ddlRoom.SelectedItem.Value));
                    lblResult.Text = "設定失敗";
                    lblResult.ForeColor = Color.Red;
                }
                else
                {
                    string strDegree = degree.ToString();
                    lblResult.Text = "設定成功!現有度數為 : " + strDegree;
                    new DBAccess().addEventLog(strAccount, strIP, 200, strMemo + " 線上繳費成功 (原有度數" + oldDegree.ToString() + "度 儲值" + tbDegree.Text + "度 現有度數" + degree.ToString() + "度)", "1", Convert.ToInt32(ddlRoom.SelectedItem.Value));
                }

                ScriptManager.RegisterStartupScript(this, this.GetType(), "HideLoading", ";document.getElementById('Loading').style.visibility='hidden';", true);
                UpdatePanel3.Visible = true;

            }
            catch (Exception ex)
            {
                lblResult.Text = "設定失敗";
                lblResult.Text += ex.Message;
                lblResult.ForeColor = Color.Red;
                UpdatePanel3.Visible = true;
            }
        }

        private void ErrorMsg(string Msg)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", ";alert('" + Msg + "');", true);
            return;
        }

        protected void tbDegree_TextChanged(object sender, EventArgs e)
        {
           
        }

        protected void ddlRoom_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlDevice.Items.Clear();
            ddlDevice.Items.Add("---");
            lOldDegree.Text = "";
            if (ddlRoom.SelectedItem.Text != "---")
            {
                string sID = ddlRoom.SelectedItem.Value;
                DataTable dt = new DBAccess_CHTD().GetPowerMeter4Fee(Convert.ToInt32(sID));  //取得寢室電錶
               
                foreach(DataRow row in dt.Rows)
                {
                    ListItem li = new ListItem(Convert.ToString(row["DeviceName"]), Convert.ToString(row["DeviceID"]));
                    ddlDevice.Items.Add(li);
                }
            }
            UpdatePanel3.Visible = false;
        }

        protected void ddlDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlDevice.SelectedItem.Text == "---")
            {
                lOldDegree.Text = "";
            }
            else
            {
                double degree = 0;
                degree = new DBAccess().getMeterBalance(ddlDevice.SelectedItem.Value);
                lOldDegree.Text = "  原有度數 : " + degree.ToString();
            }
            UpdatePanel3.Visible = false;
        }

    }
}

      